package cn.sh.library.gmwx.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class RedisService {

    private final RedisTemplate<Object, Object> redisTemplate;

    private static final String KEY_PREFIX = "gmwx_";

    // 构造器注入RedisTemplate
    public RedisService(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void save(String key,String type, Object obj) {
        redisTemplate.opsForValue().set(KEY_PREFIX + type + "_" + key, obj);
    }
    public void saveByUri(String uri, String type,Object obj) {
        redisTemplate.opsForValue().set(KEY_PREFIX + type + "_" + getKeyByUri(uri), obj);
    }

    public Object get(String key,String type) {
        return redisTemplate.opsForValue().get(KEY_PREFIX + type + "_" + key);
    }
    public Object getByUri(String uri,String type) {
        return redisTemplate.opsForValue().get(KEY_PREFIX + type + "_" + getKeyByUri(uri));
    }

    public boolean hasKey(String key, String type) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(KEY_PREFIX + type + "_" + key));
    }

    public boolean hasKeyByUri(String uri, String type) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(KEY_PREFIX + type + "_" + getKeyByUri(uri)));
    }

    private String getKeyByUri(String uri){
        if(uri == null || "".equals(uri)){
            return "";
        }
        return uri.substring(uri.lastIndexOf("/") + 1);
    }

    public byte[] serialize(Object obj) {
        ObjectOutputStream obi = null;
        ByteArrayOutputStream bai = null;
        try {
            bai = new ByteArrayOutputStream();
            obi = new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt = bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 反序列化
    public Object unserizlize(byte[] byt) {
        ObjectInputStream oii = null;
        ByteArrayInputStream bis = null;
        bis = new ByteArrayInputStream(byt);
        try {
            oii = new ObjectInputStream(bis);
            Object obj = oii.readObject();
            return obj;
        } catch (Exception e) {

            e.printStackTrace();
        }

        return null;
    }

}
